package com.higold.cloud.base

import android.annotation.SuppressLint
import android.annotation.TargetApi
import android.content.Intent
import android.net.Uri
import android.net.http.SslError
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.support.annotation.RequiresApi
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.webkit.SslErrorHandler
import android.webkit.ValueCallback
import android.webkit.WebChromeClient
import android.webkit.WebResourceError
import android.webkit.WebResourceRequest
import android.webkit.WebResourceResponse
import android.webkit.WebSettings
import android.webkit.WebView
import android.widget.LinearLayout
import com.alibaba.fastjson.JSONObject

import com.github.lzyzsd.jsbridge.BridgeWebView
import com.github.lzyzsd.jsbridge.BridgeWebViewClient
import com.higold.cloud.R
import com.kaopiz.kprogresshud.KProgressHUD
import kotlinx.android.synthetic.main.activity_common_webview.*

/**
 * 加载通用webviewWVJBWebViewClient
 *
 * @author xiehm
 * @created 2014-3-18
 */
public class BaseWebviewActivity : AppCompatActivity() {

    var js_params = JSONObject()
    internal var webview: BridgeWebView? = null
    private var ll_commom_webview: LinearLayout? = null //webview 父控件

    private var mUploadMessage: ValueCallback<Uri>? = null
    private var webViewClient: MyWebViewClient? = null

    var url: String? = ""

    private var wcci: WebChromeClient = object : WebChromeClient() {
        // For Android 3.0+
        fun openFileChooser(uploadMsg: ValueCallback<Uri>) {
            mUploadMessage = uploadMsg
        }

        // For Android 3.0+
        fun openFileChooser(uploadMsg: ValueCallback<Uri>, acceptType: String) {
            mUploadMessage = uploadMsg
        }

        //For Android 4.1
        fun openFileChooser(uploadMsg: ValueCallback<Uri>, acceptType: String, capture: String) {
            mUploadMessage = uploadMsg
        }
    }

    @SuppressLint("SetJavaScriptEnabled")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_common_webview)

        val js_params = intent.getStringExtra("js_params")
        Log.e("js_params", js_params)

        this.js_params = JSONObject.parseObject(js_params)

        initView()


    }

    @SuppressLint("SetJavaScriptEnabled", "LongLogTag")
    fun initView() {

        url = this.js_params.getString("target")

        ll_commom_webview = findViewById(R.id.ll_commom_webview) as LinearLayout

        webview = findViewById(R.id.wb_act) as BridgeWebView
        //webview.setVisibility(View.GONE);

        val webSettings = webview!!.settings
        webSettings.allowFileAccess = true
        webSettings.javaScriptEnabled = true
        webSettings.domStorageEnabled = true //百度地图加载

        val ua = webview!!.settings.userAgentString

        webSettings.userAgentString = "$ua;general"

        webview!!.webChromeClient = wcci
        webViewClient = MyWebViewClient(webview!!)
        webview!!.webViewClient = webViewClient //用定义的webviewclient
        //webview.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
        //webview.setVerticalScrollBarEnabled(false); //垂直不显示  滚动条
        webSettings.defaultTextEncodingName = "utf-8"

        webSettings.useWideViewPort = true
        webSettings.loadWithOverviewMode = true
        webSettings.layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN

        webSettings.blockNetworkImage = false//解除阻止

        webSettings.blockNetworkLoads = false//

        webSettings.cacheMode = WebSettings.LOAD_NO_CACHE

        webSettings.setAppCacheEnabled(false)//不缓存

        webview!!.loadUrl("file:////android_asset/1.0/index.html#$url")

        iv_back.setOnClickListener { finish() }

        webview!!.registerHandler("setNavBarTitle") { data, _ ->
            val data_json = JSONObject.parseObject(data.toString())
            tv_title.text = data_json["title"].toString()
        }

        webview!!.registerHandler("push") { data, function ->
            //显示接收的消息

            val data_json = JSONObject.parseObject(data.toString())


            if (data_json.getString("type") == "native") {

                var activityClass: Class<*>? = null //跳到其他原生页面
                try {
                    activityClass = Class.forName(data_json.getString("target"))
                } catch (e: ClassNotFoundException) {
                    e.printStackTrace()
                }

                val intent = Intent(this@BaseWebviewActivity, activityClass)

                intent.putExtra("js_params", data_json.toString())

                if (data_json.getString("animated") == "true") {

                    //加动画

                } else {
                    //没动画
                }

                startActivity(intent)//启动Activity

            } else {

                val intent = Intent(this@BaseWebviewActivity, BaseWebviewActivity::class.java)

                intent.putExtra("js_params", data_json.toString())

                if (data_json.getString("animated") == "true") {

                    //加动画

                } else {
                    //没动画
                }

                startActivity(intent)//启动Activity
            }
        }

        webview!!.registerHandler("getCurrentVCJsParams") { data, function ->
            //显示接收的消息
            try {

                val result_json = org.json.JSONObject(this@BaseWebviewActivity.js_params.toString())
                Log.e("result", result_json.toString())
                function.onCallBack(result_json.toString())

            } catch (e: org.json.JSONException) {
                e.printStackTrace()
            }
        }

    }

    inner class MyWebViewClient(webView: BridgeWebView) : BridgeWebViewClient(webView) {

        override fun onPageFinished(view: WebView, url: String) {
            super.onPageFinished(view, url)
        }

        override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
            return super.shouldOverrideUrlLoading(view, url)
        }

        override fun onReceivedHttpError(
                view: WebView,
                request: WebResourceRequest,
                errorResponse: WebResourceResponse
        ) {

            super.onReceivedHttpError(view, request, errorResponse)

            Log.e("onReceivedHttpError", "onReceivedHttpError进来了")

        }

        override fun onReceivedError(view: WebView, request: WebResourceRequest, error: WebResourceError) {
            super.onReceivedError(view, request, error)

            Log.e("onReceivedError", "onReceivedError进来了")
        }


        //添加下面2行代码来忽略SSL验证
        override fun onReceivedSslError(view: WebView, handler: SslErrorHandler, error: SslError) {
            handler.proceed()
        }


    }

    @SuppressLint("RestrictedApi")
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    override fun startActivityForResult(intent: Intent, requestCode: Int, options: Bundle?) {
        super.startActivityForResult(intent, requestCode, options)
    }


    companion object {
        private val FILECHOOSER_RESULTCODE = 1


        private val MINI_TYPE = "text/html; charset=UTF-8"
        private val ENCODING = "UTF-8"

        var refresh_handler: Handler? = null //刷新界面通知
    }

}

